python smtp
gmail 例子
# coding:cp936 import sys , os import glob import time import smtplib import mimetypes from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEAudio import MIMEAudio from email.MIMEImage import MIMEImage from email.Encoders import encode_base64 usr = 'username' psw = 'password' class Gmail : '''''' def __init__(self,usr,psw) : # Credentials (if needed) self.usr= usr self.psw = psw self.fromaddr = self.usr+'@gmail.com' self.g = smtplib.SMTP('smtp.gmail.com:587') self.g.starttls() def send(self,files) : msg = MIMEMultipart() #msg = MIMEText('gmail cloud') msg["Subject"] = 'Gloud ' + files msg['From'] = self.fromaddr msg['To'] = self.fromaddr msg.attach(MIMEText('gmail cloud')) filenames = filter(os.path.isfile, glob.glob(files)) for filename in filenames: msg.attach(self.getAttachment(filename)) print 'add' , filename self.g.login(self.usr,self.psw) print 'login gmail as' , self.usr self.g.sendmail(self.fromaddr, self.fromaddr, msg.as_string()) self.g.quit() print 'logout gmail' def getAttachment(self,attachmentFilePath): contentType, encoding = mimetypes.guess_type(attachmentFilePath) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) fp = open(attachmentFilePath, 'rb') content = fp.read() #if mainType == 'text': #attachment = MIMEText(fp.read()) #elif mainType == 'message': #attachment = email.message_from_file(fp) #elif mainType == 'image': #attachment = MIMEImage(fp.read(),_subType=subType) #elif mainType == 'audio': #attachment = MIMEAudio(fp.read(),_subType=subType) #else: #attachment = MIMEBase(mainType, subType) attachment = MIMEBase(mainType, subType) attachment.set_payload(content) encode_base64(attachment) fp.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) return attachment if __name__ == "__main__" : '''''' ts = time.time() if len(sys.argv) != 2 : sys.exit(0) files = sys.argv[1] gmail = Gmail(usr,psw) gmail.send(files) te = time.time() print 'Total Time:' , te-ts , 's'
Send Mail Through Gmail with Python
Python is a great scripting language for Linux and it is often used to automate tasks or check on overall system health. Discover how to send emails through Gmail with Python.
Good system admins get to know scripting languages well and sometimes use them for all kinds of purposes, from scripts that do backups to complex automated tasks. Often times it would be nice to get an email notification when the script finished or completed OK. Cron does a good job of sending emails when scripts run into errors or problems, but sometimes it is necessary to get custom email messages sent from the script itself. Python makes sending email alerts a breeze.
The Code
import smtplib fromaddr = 'fromuser@gmail.com' toaddrs = 'touser@gmail.com' msg = 'There was a terrible error that occured and I wanted you to know!' # Credentials (if needed) username = 'username' password = 'password' # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit()
What Now?
You will want to use this with an already existing script or a script where you want to add email alerts. For example:
# A big task ... if task.completedOk(): # Insert email code here, explaining that # the task is done and some details about it
Or perhaps you wanted Python to send you an email if the server room gets too hot:
# Get temp ... if temperature > 70: # Insert email code here